from django.db.models import F
from django.test import TestCase

# Create your tests here.
#单元测试
from apitest.models import UserInfo, Author, AuthorDetail, Book


#独立数据库
class UserInfoTest(TestCase):

    def test_addUser(self):
        #insert  into
        UserInfo.objects.create(name='mtx',password='1212',age=20)

        UserInfo.objects.create(**{"name": "bbb", "password": "test", "age": 20})


        obj = UserInfo(name='alex', password='123')
        obj.save()


        #
        # userlist = UserInfo.objects.all()
        # for item in userlist:
        #     print(item.name,item.password)

        userlist = UserInfo.objects.filter(name='mtx')
        for item in userlist:
            print(item.name,item.password)

        userinfo = UserInfo.objects.get(pk=1)
        print(userinfo.name,userinfo.password)

        userlist = UserInfo.objects.raw('select * from userinfo where id>1')
        print(type(userlist))

        UserInfo.objects.filter(id__gt=1)

    def test_addBooks(self):
        # au = Author(author_name='zhangsan')
        # au.save()
        # authorlist=   Author.objects.all()
        # for item in authorlist:
        #     print(item.author_name)
        # au_detail =  AuthorDetail(author_sex=1,author_phone='111111',author = au)
        # au_detail.save()
        # usrlist=  AuthorDetail.objects.all()
        # for item in usrlist:
        #     print(item.author.author_name,item.author_phone)

        # Author.objects.all().delete()
        #
        # usrlist = AuthorDetail.objects.all()
        # print(usrlist)
        # for item in usrlist:
        #     print(item.author.author_name, item.author_phone)
        #多对多
        au1 = Author(author_name='zhangsan1')
        au1.save()

        au2 = Author(author_name='zhangsan2')
        au2.save()

        au3 = Author(author_name='zhangsan3')
        au3.save()

        b1 = Book(book_name='海底2万里', price=11.2)
        b1.save()
        #添加add
        b1.author.add(au1)
        b1.author.add(au2)
        # b1.author.remove(au1)  # 移除关联对象

        b2 = Book(book_name='python入门', price=31.2)
        b2.save()
        b2.author.add(au3)
        booklist = Book.objects.all()
        for item in booklist:
            print(item.price)
            # 多对多数据获取
            for author in item.author.all():
                print(author.author_name)

            print(list(item.author.all().values()))

        print("分割符号。。。。")
        booklist = list(Book.objects.all().values('book_name'))
        print(booklist)

        books = list(Book.objects.all().values('id', 'book_name', 'author__author_name'))
        print(books)










